﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChip_Common;
using XChipTool.Enties;
using System.IO.Ports;
using SerialPortHelperLib;
using System.Threading;
using System.IO;
using NPOI.HSSF.UserModel;
using System.Text.RegularExpressions;

namespace XChipTool
{
    public partial class XChip_RegTable : DevExpress.XtraEditors.XtraUserControl
    {
        #region 全局变量

        CommandTxt cT;

        //private  xc128registerManager registerDal ;

        //private  xcmainregisterManager xregitsterDal ;

        public SerialPort sPortTemp;

        public List<xc128register> rList = new List<xc128register>();

        public List<xc151register> r151List = new List<xc151register>();
        ///// <summary>
        ///// 创建上下文同步
        ///// </summary>
        private SynchronizationContext context;

        //public xc128registerManager RegisterDal { get; set; }

        public xc151registerManager Register151Dal { get; set; }

        //public xcmainregisterManager XregitsterDal { get; set; }
        /// <summary>
        /// 是否在赋值
        /// </summary>
        private bool isFuBool = false;
        /// <summary>
        /// 滚动条是否可编辑
        /// </summary>
        private bool isParBool = false;
        /// <summary>
        /// 是否需要添加
        /// </summary>
        private bool isCuteBool { get; set; } = false;
        /// <summary>
        /// 记录选中的地址
        /// </summary>
        private string AddressTemp = string.Empty; 
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        private int ReadBitTemp = -1;
        /// <summary>
        /// 主表
        /// </summary>
        private List<xcmainregister> xrList = new List<xcmainregister>();
        /// <summary>
        /// 从表
        /// </summary>
        private List<xc128register> rlist = new List<xc128register>();
        /// <summary>
        /// 主表选中行
        /// </summary>
        private int gridView1RowHandle = 0;
        /// <summary>
        /// 从表选中行
        /// </summary>
        private int gridView2RowHandle = 0;
        #endregion
        public XChip_RegTable()
        {
            InitializeComponent();
        }


        public XChip_RegTable(SerialPort _sPortTemp, xc151registerManager _RegisterDal)
        {
               sPortTemp = _sPortTemp;
            Register151Dal = _RegisterDal;
            //XregitsterDal = _XregitsterDal;
            InitializeComponent();
        }
        private void textEdit2_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textEdit2.Text)) return;
            isFuBool = true;
            //设置RegisterSliding 值
            var rNum = Convert.ToInt32(textEdit2.Text, 16);
           
            //设置RegisterCheck 值二进制值
            var erNum = Convert.ToString(rNum, 2).PadLeft(32, '0');
            for (int i = 0; i < erNum.Length; i++)
            {
                var tempNum = 32 - i;

                #region 代码折叠
                if (tempNum > 28)
                {

                    foreach (Control item in groupBox7.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {

                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                }
                else if (tempNum <= 28 && tempNum > 24)
                {

                    foreach (Control item in groupBox6.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                }
                else if (tempNum <= 24 && tempNum > 20)
                {

                    foreach (Control item in groupBox5.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                }
                else if (tempNum <= 20 && tempNum > 16)
                {

                    foreach (Control item in groupBox4.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                }
                else if (tempNum <= 16 && tempNum > 12)
                {

                    foreach (Control item in groupBox3.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                }
                else if (tempNum <= 12 && tempNum > 8)
                {

                    foreach (Control item in groupBox2.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }

                }
                else if (tempNum <= 8 && tempNum > 4)
                {

                    foreach (Control item in groupBox1.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                }
                else if (tempNum <= 4)
                {

                    foreach (Control item in groupBox0.Controls)
                    {
                        if (item.Name == $"RegisterCheck{tempNum}")
                        {
                            if (erNum[i] == '1')
                            {
                                (item as CheckEdit).Checked = true;
                            }
                            else
                            {
                                (item as CheckEdit).Checked = false;
                            }
                        }
                    }
                } 
                #endregion

            }
            //刷新表格数据
            //地址  addressTxt.Text;
            r151List.ForEach(c => {
                if (c.Address == addressTxt.Text)
                {
                    c.ResetValue = textEdit2.Text;
                }
            });
            var aut = gongnengEdit.EditValue.ToString();
            gridControl1.DataSource = r151List.Where(c => c.Author == aut).ToList();
            //设置选中行
            gridView1.FocusedRowHandle = gridView1RowHandle;
            gridView1.RefreshData();

            var tempList = r151List.Where(c => c.Address == addressTxt.Text).ToList();
            //修改
            tempList.ForEach(c => {
                //判断位数 
                c.ResetValue = c.Bits.Contains(":") ? BitsHelp.GetBits(c.Bits, textEdit2.Text).ToString("X2") : BitsHelp.GetBits(c.Bits, textEdit2.Text).ToString("X1");
            });
            //处理list
            gridControl2.DataSource = tempList;
            gridView2.FocusedRowHandle = gridView2RowHandle;
            gridView2.RefreshData();
            //添加撤销
            cT.execute(new ExecuteTxt() { gridView1_RowHandle = this.gridView1.FocusedRowHandle, gridView2_RowHandle = this.gridView2.FocusedRowHandle, textEdit = textEdit2.Text });
            undoBtn.Enabled = cT.CanUndo;
            redoBtn.Enabled = cT.CanRedo;
            isFuBool = false;
        }

        private void XChip_RegTable_Load(object sender, EventArgs e)
        {
            if (context == null)
            {
                context = SynchronizationContext.Current;
            }
            undoBtn.Enabled = false;
            redoBtn.Enabled = false;
            //设置最大次幂值
            RegisterSliding.Properties.Minimum = 0;
            var powTemp = Math.Pow(2, 31) - 1;
            RegisterSliding.Properties.Maximum = (int)powTemp;
           
             NewRegRefresh();


        }

        private void NewRegRefresh()
        {
            context.Post(t => {
                //if (XregitsterDal !=null)
                //{
                //    xrList = XregitsterDal.GetList();
                //    var list = xrList.Select(c => c.Author).Distinct().ToList();
                //    gongnengEdit.Properties.DataSource = list;
                //    gongnengEdit.ItemIndex = 0;
                //}
                if(Register151Dal != null)
                {
                    r151List = Register151Dal.GetList();
                    gongnengEdit.Properties.DataSource = r151List.Select(c=>c.Author).Distinct().ToList();
                    gongnengEdit.ItemIndex = 0;
                }   
            },"");
                  
        }



        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            isCuteBool = true;
            //撤销
            cT.undo();
           

            if (null != cT.Record && cT.Record.gridView1_RowHandle >= 0 && cT.Record.gridView1_RowHandle == gridView1.FocusedRowHandle)
            {
                textEdit2.Text = cT.Record.textEdit;
                gridView1.FocusedRowHandle = cT.Record.gridView1_RowHandle;
                gridView1.RefreshData();
                gridView2.FocusedRowHandle = cT.Record.gridView2_RowHandle;
                gridView2.RefreshData();
            }
          

            undoBtn.Enabled = cT.CanUndo;
            redoBtn.Enabled = cT.CanRedo;
            isCuteBool = false;
        }
        /// <summary>
        /// 恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            isCuteBool = true;
            cT.redo();            
            if (null !=cT.Record && cT.Record.gridView1_RowHandle >= 0&& cT.Record.gridView1_RowHandle == gridView1.FocusedRowHandle)
            {
                textEdit2.Text = cT.Record.textEdit;
                gridView1.FocusedRowHandle = cT.Record.gridView1_RowHandle;
                gridView1.RefreshData();
                gridView2.FocusedRowHandle = cT.Record.gridView2_RowHandle;
                gridView2.RefreshData();
            }
           
            undoBtn.Enabled = cT.CanUndo;
            redoBtn.Enabled = cT.CanRedo;
            isCuteBool = false;
        }

        public class RegisterComparer : IEqualityComparer<xc128register>
        {
            public bool Equals(xc128register x, xc128register y)
            {
                return x.Address == y.Address ;
            }
            public int GetHashCode(xc128register obj)
            {
                return obj.Address.GetHashCode();
            }
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            isFuBool = true;
            // 当前选定行
            int i = gridView1RowHandle = this.gridView1.FocusedRowHandle;
            gridView2RowHandle = this.gridView2.FocusedRowHandle;
            //选中行,列名为name的值
            var baseadd = AddressTemp = gridView1.GetRowCellDisplayText(i, gridView1.Columns["Address"]);            
            //赋值文本值  发送时候使用
            addressTxt.Text = AddressTemp;           
            //var addoff =  gridView1.GetRowCellDisplayText(i, gridView1.Columns["AddressOffset"]);
            var auth =  gridView1.GetRowCellDisplayText(i, gridView1.Columns["Author"]);
            var data = gridView1.GetRowCellDisplayText(i, gridView1.Columns["ResetValue"]);
            var readbit   = gridView1.GetRowCellDisplayText(i, gridView1.Columns["ReadBit"]);
            ReadBitTemp = int.Parse(readbit);
            var readwrite = gridView1.GetRowCellDisplayText(i, gridView1.Columns["ReadWrite"]).Replace("/","");
            var mask = gridView1.GetRowCellDisplayText(i, gridView1.Columns["Mask"]);
            //读取值
            string str = string.Empty;

            //var TempRst= data;
            default_value.Text = data;
            simpleButton4.Enabled = true; //默认值按钮使能
            labelControl10.Text = readwrite;
            labelControl12.Text = mask;            
            //labelControl13.Text = null;
            #region 勾选框使能
            #region 关闭全部
            //关闭全部
            foreach (Control item in groupBox0.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox1.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox2.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox3.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox4.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox5.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox6.Controls)
            {
                item.Enabled = false;
            }
            foreach (Control item in groupBox7.Controls)
            {
                item.Enabled = false;
            }
            #endregion
            switch (ReadBitTemp)
            {
                case 1:
                    RegisterCheck1.Enabled = true;
                    RegisterCheck2.Enabled = true;
                    RegisterCheck3.Enabled = true;
                    RegisterCheck4.Enabled = true;
                    RegisterCheck5.Enabled = true;
                    RegisterCheck6.Enabled = true;
                    RegisterCheck7.Enabled = true;
                    RegisterCheck8.Enabled = true;
                    break;
                case 4:
                    {
                        #region 打开全部                        
                        foreach (Control item in groupBox0.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox1.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox2.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox3.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox4.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox5.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox6.Controls)
                        {
                            item.Enabled = true;
                        }
                        foreach (Control item in groupBox7.Controls)
                        {
                            item.Enabled = true;
                        }
                        #endregion
                    }

                    break;
                default:
                    break;
            } 
            #endregion

            if (null!= sPortTemp&&sPortTemp.IsOpen)
            {
                for (int j = int.Parse(readbit) -1; j >= 0; j--)
                {
                    var add = (Convert.ToUInt32(AddressTemp, 16) + (uint)j);
                    str += SerialSend.ReadRegister(add, sPortTemp).ToString("X2");
                }
            }
            //不为空就赋值
            if (!string.IsNullOrEmpty(str) && data != str)
            {
                data = str;
                //xrList.ForEach(c => {
                //    if (c.Address == AddressTemp)
                //    {
                //        c.ResetValue = str;
                //    }
                //});
                //gridControl1.DataSource = xrList;
                //设置选中行
                //gridView1.FocusedRowHandle = gridView1RowHandle;
                //gridView1.RefreshData();
            }

          
            //rlist = RegisterDal.GetList(c=>c.Author == auth);
            var tempList = r151List.Where(c => c.Address.ToLower() == baseadd.ToLower()).ToList();
            //修改
            //if (!string.IsNullOrEmpty(data))
            //{
            //    tempList.ForEach(c => {
            //        //判断位数 
            //        c.Data = c.Bits.Contains(":") ? BitsHelp.GetBits(c.Bits, data).ToString("X2") : BitsHelp.GetBits(c.Bits, data).ToString("X1");
            //    });
            //}
          
            cT = null;
            //设置重置最大次数
            cT = new CommandTxt(50);
            //文本框赋值
            textEdit2.Text = data;
            //添加撤销
            //cT.execute(new ExecuteTxt() { gridView1_RowHandle = this.gridView1.FocusedRowHandle, gridView2_RowHandle = this.gridView2.FocusedRowHandle, textEdit = data });
            //设置滚动条禁止
            RegisterSliding.Enabled = false;
            //处理list
            gridControl2.DataSource = tempList;
            gridView2.RefreshData();
           

           
            undoBtn.Enabled = cT.CanUndo;
            redoBtn.Enabled = cT.CanRedo;
            isFuBool = false;
        }


        /// <summary>
        /// 选择模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gongnengEdit_EditValueChanged(object sender, EventArgs e)
        {
            var aut = gongnengEdit.EditValue.ToString();
            //if (xrList.Where(c => c.Author == aut).Count() <= 0)
            //{
                //xrList = r151List.Where(c => c.Author == aut).ToList();
            //}
            this.gridControl2.DataSource = null;
            gridView2.RefreshData();
            gridControl1.DataSource = r151List.Where(c => c.Author == aut).ToList(); 
            gridView1.RefreshData();
        }

        private void gridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            isParBool = true;
            gridView2.OptionsView.RowAutoHeight = true;
            // 当前选定行
            gridView1RowHandle = this.gridView1.FocusedRowHandle;
            int i = gridView2RowHandle = this.gridView2.FocusedRowHandle;
            var name = gridView2.GetRowCellDisplayText(i, gridView2.Columns["Subset"]);
            //判断显示多少chechek框
            var auth = gridView2.GetRowCellDisplayText(i, gridView2.Columns["Bits"]);
            //显示文本值
            var data = gridView2.GetRowCellDisplayText(i, gridView2.Columns["ResetValue"]);
            var mask = gridView2.GetRowCellDisplayText(i, gridView2.Columns["Mask"]);
            labelControl12.Text = mask;
            labelControl13.Text = name;

           //添加撤销
           //cT.execute(new ExecuteTxt() { gridView1_RowHandle = this.gridView1.FocusedRowHandle, gridView2_RowHandle = this.gridView2.FocusedRowHandle, textEdit = textEdit2.Text });

           var authList = auth.Replace("[", "").Replace("]", "").Split(':');

            //文本框赋值
            tenTxt.Text = Convert.ToUInt32(data, 16).ToString();
            sixteenTxt.Text = data;

            switch (authList.Count())
            {
                case 1:
                    {
                        int autNum = int.Parse(authList[0]) + 1;
                        //表示只有一个bit  所以可以直接打开对应的chech
                        #region 关闭和打开check
                        foreach (Control item in groupBox0.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox1.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox2.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox3.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox4.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox5.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox6.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        foreach (Control item in groupBox7.Controls)
                        {
                            if (item.Name == $"RegisterCheck{autNum}")
                            {
                                item.Enabled = true;
                            }
                            else
                            {
                                item.Enabled = false;
                            }
                        }
                        #endregion

                        RegisterSliding.Enabled = true;
                        //设置滚动条
                        RegisterSliding.Properties.Maximum = 1;
                        var jinNum = Convert.ToInt32(tenTxt.Text);
                        RegisterSliding.Value = jinNum;
                    }
                    break;
                case 2:
                    {
                        #region 关闭全部
                        //关闭全部
                        foreach (Control item in groupBox0.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox1.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox2.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox3.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox4.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox5.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox6.Controls)
                        {
                            item.Enabled = false;
                        }
                        foreach (Control item in groupBox7.Controls)
                        {
                            item.Enabled = false;
                        }
                        #endregion

                        #region 打开范围部分数据
                        //表示范围1
                        int autNum1 = int.Parse(authList[0]) + 1;
                        //表示范围2
                        int autNum2 = int.Parse(authList[1]) + 1;
                        //获取二进制最大值
                        string erNum = string.Empty;

                        for (int b = autNum2; b <= autNum1; b++)
                        {
                            erNum += "1";
                            foreach (Control item in groupBox0.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox1.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox2.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox3.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox4.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox5.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox6.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                            foreach (Control item in groupBox7.Controls)
                            {
                                if (item.Name == $"RegisterCheck{b}")
                                {
                                    item.Enabled = true;
                                }
                            }
                        }
                        #endregion

                        //设置滚动条范围
                        //二进制转十进制
                        if (erNum == "11111111111111111111111111111111") //表示全部开放则不滚动条禁止
                        {
                            RegisterSliding.Enabled = false;
                        }
                        else {
                            RegisterSliding.Enabled = true;
                            var eNum = Convert.ToInt32(erNum, 2);
                            //设置滚动条最大值
                            RegisterSliding.Properties.Maximum = eNum;
                            //设置滚动条值
                            var jinNum = Convert.ToInt32(tenTxt.Text);
                            RegisterSliding.Value = jinNum;
                        }
                       
                    }
                    break;
                default:
                    break;
            }
            isParBool = false;           
        }
        /// <summary>
        /// check勾选框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterCheck32_CheckedChanged(object sender, EventArgs e)
        {
            if (!isFuBool)
            {
                int[] erNum = new int[32];
                #region 选择勾选框
                for (int i = 0; i < 32; i++)
                {
                    var temp = i + 1;
                    foreach (Control item in groupBox0.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox1.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox2.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox3.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox4.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox5.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox6.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                    foreach (Control item in groupBox7.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            erNum[i] = (item as CheckEdit).Checked ? 1 : 0;
                        }
                    }
                }

                #endregion
                //int 数组转换成二进制数
                string erN = string.Empty;
                for (int i = erNum.Count() - 1; i >= 0; i--)
                {
                    erN += erNum[i];
                }
                //二进制转成16进制数
                switch (ReadBitTemp)
                {
                    case 4:
                        textEdit2.Text = string.Format("{0:X8}", System.Convert.ToInt32(erN, 2));
                        break;
                    case 1:
                        textEdit2.Text = string.Format("{0:X2}", System.Convert.ToInt32(erN, 2));
                        break;
                    default:
                        break;
                }               
            }   
           
        }
        /// <summary>
        /// 滚动条修改值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterSliding_EditValueChanged(object sender, EventArgs e)
        {
            if (!isParBool)
            {
                
                //设置勾选框需要赋值的范围勾选
                int maxCheck = -1;
                int minCheck = 32;
                for (int i = 0; i < 32; i++)
                {
                    var temp = i + 1;
                    foreach (Control item in groupBox0.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox1.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox2.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox3.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox4.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox5.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox6.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                    foreach (Control item in groupBox7.Controls)
                    {
                        if (item.Name == $"RegisterCheck{temp}")
                        {
                            if ((item as CheckEdit).Enabled)
                            {
                                int Ctemp = int.Parse(item.Tag.ToString());
                                maxCheck = Ctemp > maxCheck ? Ctemp : maxCheck;
                                minCheck = Ctemp < minCheck ? Ctemp : minCheck;
                            }
                        }
                    }
                }
                int checkNumTemp = (maxCheck - minCheck)+1;
                //获取滚动条值 并且转换成二进制值
                var erNum = Convert.ToString(RegisterSliding.Value, 2).PadLeft(checkNumTemp, '0').ToList();
                //设置check
                for (int i =  minCheck; i <= maxCheck; i++)
                {
                    foreach (Control item in groupBox0.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp-1-(i - minCheck))])=='0'?false:true;
                        }
                    }
                    foreach (Control item in groupBox1.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                    foreach (Control item in groupBox2.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                    foreach (Control item in groupBox3.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                    foreach (Control item in groupBox4.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                    foreach (Control item in groupBox5.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                    foreach (Control item in groupBox6.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                    foreach (Control item in groupBox7.Controls)
                    {
                        if (item.Name == $"RegisterCheck{i}")
                        {
                            (item as CheckEdit).Checked = (erNum[(checkNumTemp - 1 - (i - minCheck))]) == '0' ? false : true;
                        }
                    }
                }

            }
            //赋值文本框
            tenTxt.Text = RegisterSliding.Value.ToString();
            sixteenTxt.Text = Convert.ToInt32(tenTxt.Text, 10).ToString("X2");
        }
        /// <summary>
        /// 下发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click_1(object sender, EventArgs e)
        {
            var add = Convert.ToUInt32(addressTxt.Text, 16);            
            switch (ReadBitTemp)
            {
                case 1:
                    var val = Convert.ToUInt32(textEdit2.Text, 16);
                    SerialSend.WriteRegister(add, val, sPortTemp);
                    break;
                case 4:
                    for (uint i = 0; i < 4; i++)
                    {
                        var tempVal = Convert.ToUInt32(textEdit2.Text.Substring((int)i*2, 2),16);
                        SerialSend.WriteRegister((add+3-i), tempVal, sPortTemp);
                    }
                    
                    break;
                default:
                    break;
            }           
        }

        private void simpleButton4_Click_1(object sender, EventArgs e)//默认值按钮
        {
            textEdit2.Text = default_value.Text;
        }
        /// <summary>
        /// 刷新页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton6_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            var aut = gongnengEdit.EditValue.ToString();
            WaitBefore.Start("读取中.", "正在加载中", 20);
            foreach (var item in r151List.Where(c => c.Author == aut).ToList())
            {
                var str = string.Empty;
                //if (null != sPortTemp && sPortTemp.IsOpen)
                
                    
                        var add = (Convert.ToUInt32(item.Address, 16));
                        str += SerialSend.ReadRegister(add, sPortTemp).ToString("X2");
                    
                
                //不为空就赋值
                if (!string.IsNullOrEmpty(str))
                {
                    r151List.ForEach(c => {
                        if (c.Address == item.Address)
                        {
                            c.ResetValue = str;
                        }
                    });
                }
            }
           
            gridControl1.DataSource = r151List.Where(c => c.Author == aut).ToList();
            //设置选中行
            gridView1.FocusedRowHandle = gridView1RowHandle;
            gridView1.RefreshData();
            WaitBefore.Close();

        }

      

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            var TempText = sender as DevExpress.XtraEditors.TextEdit;
            if (!string.IsNullOrEmpty(TempText.Text))
            {
                var aut = gongnengEdit.EditValue.ToString();
                var list =  r151List.Where(c => c.Author == aut&&(c.Address.Contains(TempText.Text)||c.BaseAddr.Contains(TempText.Text)||c.AddrOffset.Contains(TempText.Text))).ToList();
                gridControl1.DataSource = list;
                this.gridControl2.DataSource = null;
                gridView2.RefreshData();
                gridView1.RefreshData();
                return;
            }
            else
            {
                var aut = gongnengEdit.EditValue.ToString();
                var list = r151List.Where(c => c.Author == aut ).ToList();
                gridControl1.DataSource = list;
                this.gridControl2.DataSource = null;
                gridView2.RefreshData();
                gridView1.RefreshData();
            }


        }

        private void gridView2_CalcRowHeight(object sender, DevExpress.XtraGrid.Views.Grid.RowHeightEventArgs e)
        {
            //获得字体的宽度和高度。
            Graphics graphics = CreateGraphics();
            SizeF sizef = graphics.MeasureString(gridView2.GetRowCellValue(e.RowHandle, "Description").ToString(), gridView2.Appearance.Row.Font);
            SizeF sizer = new SizeF();
            if (!string.IsNullOrEmpty(gridView2.GetRowCellValue(e.RowHandle, "RegisterName").ToString()))
            {
                 sizer = graphics.MeasureString(gridView2.GetRowCellValue(e.RowHandle, "RegisterName").ToString(), gridView2.Appearance.Row.Font);
            }
            
            //根据字体的宽度除以这列的宽度计算得出需要几行。使用Ceiling把小数都进一位成整数
            double doub = Math.Ceiling(sizef.Width / gridView2.Columns["Description"].Width);
            double dour = Math.Ceiling(sizer.Width / gridView2.Columns["RegisterName"].Width);
            //设置行高为需要几行乘以这个字体的高度
            if (doub>dour)
            {
                e.RowHeight = (int)(doub * sizef.Height);
            }
            else
            {
                e.RowHeight = (int)(dour * sizer.Height);
            }
           
        }
        /// <summary>
        /// 用于测试excel 导入工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入文件（*.xls）|*.xls";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {

                var fs = new FileStream(sfd.FileName, FileMode.Open, FileAccess.Read);
                var workbook = new HSSFWorkbook(fs);
                //var dt = NPOIOprateExcel.ToExcelDataTable(workbook, 6);
                var SList = NPOIOprateExcel.GetSheetName(workbook);
                List<xc151register> xclist = new List<xc151register>();

                foreach (var item in SList)
                {
                    if (item.ToLower().Contains("read me")) continue;
                    var sheetid = workbook.GetSheetIndex(item);
                    DataTable dt = NPOIOprateExcel.ExcelToDataTables(sfd.FileName, sheetid,6);
                    //处理dt
                    string _subset = string.Empty;
                    string _baseAddr = string.Empty;
                    string _desTxt = string.Empty;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                       
                        DataRow dr = dt.Rows[i];
                        if (string.IsNullOrEmpty(dr["column2"].ToString())&& string.IsNullOrEmpty(dr["column3"].ToString()) && string.IsNullOrEmpty(dr["column4"].ToString()))
                        {
                            continue;
                        }

                        if (dr["column2"].ToString() == "Bits")
                        {
                            _subset = dt.Rows[i - 1]["column1"].ToString();
                            _baseAddr = dr["column1"].ToString();
                            continue;
                        }

                        if (string.IsNullOrEmpty(_desTxt) || (_desTxt != dr["column5"].ToString()&&!string.IsNullOrEmpty(dr["column5"].ToString())))
                        {
                            _desTxt = dr["column5"].ToString();
                        }

                        if (!string.IsNullOrEmpty(_subset)&&!string.IsNullOrEmpty(_baseAddr))
                        {
                            if (dr["column2"].ToString().Contains("…") && dr["column1"].ToString().Contains("…"))
                            {
                                var minNo = Convert.ToUInt32(dt.Rows[i - 1]["column1"].ToString().Replace("0x", ""), 16);
                                var maxNo = Convert.ToUInt32(dt.Rows[i + 1]["column1"].ToString().Replace("0x", ""), 16);

                                //var rn = dt.Rows[i - 1]["column3"].ToString().Substring(0, dt.Rows[i - 1]["column3"].ToString().IndexOf('['));
                                //string pattern = @"^(\w+)(\[\d+\])?(\[\d+:\d+\])?$";
                                //Regex regex = new Regex(pattern);
                                //Match match = regex.Match(dt.Rows[i - 1]["column3"].ToString());
                                //string name1 = string.Empty, name2 = string.Empty, index1_1 = string.Empty, index1_2 = string.Empty, index2_1 = string.Empty, index2_2 = string.Empty;
                                //if (match.Success)
                                //{
                                //    name1 = match.Groups[1].Value;
                                //    index1_1 = match.Groups[2].Value;
                                //    index2_1 = match.Groups[3].Value;

                                //}
                                //match = regex.Match(dt.Rows[i + 1]["column3"].ToString());
                                //if (match.Success)
                                //{
                                //    name2 = match.Groups[1].Value;
                                //    index1_2 = match.Groups[2].Value;
                                //    index2_2 = match.Groups[3].Value;

                                //}

                              
                                    
                                    for (uint j = minNo; j < maxNo-1; j++)
                                    {
                                       
                                            xc151register model1 = new xc151register();
                                            model1.BaseAddr = _baseAddr;
                                            model1.AddrOffset = (j + 1).ToString("X4");
                                            model1.Address = $"{model1.BaseAddr}{model1.AddrOffset }";
                                            model1.Author = item;
                                            model1.Subset = _subset;
                                            model1.ReadWrite = dt.Rows[i - 1]["column4"].ToString();
                                            model1.RegisterName = "…";
                                            model1.Description = "…";
                                            model1.Bits = dt.Rows[i - 1]["column2"].ToString();
                                            model1.Mask = HexToMask(model1.Bits);
                                            //这里先设置为0
                                            model1.ResetValue = "0x0";
                                            model1.ReadBit = "1";
                                            xclist.Add(model1);
                                        
                                        
                                    }
                                
                                continue;
                            }

                            xc151register model = new xc151register();
                            model.BaseAddr = _baseAddr;
                            model.AddrOffset = dr["column1"].ToString().Replace("0x", "");
                            model.Address = $"{model.BaseAddr}{model.AddrOffset }";
                            model.Author = item;
                            model.Subset = _subset;
                            model.ReadWrite = dr["column4"].ToString();
                            model.RegisterName = dr["column3"].ToString();
                            model.Description = _desTxt;
                            model.Bits = dr["column2"].ToString();
                            model.Mask = HexToMask(model.Bits);
                            //这里先设置为0
                            model.ResetValue = "0x0";
                            model.ReadBit = "1";
                            xclist.Add(model);
                        }
                    }
                }

                xc151registerManager xc151 = new xc151registerManager();
                xc151.Insert(xclist);


            }
        }

        private static string  HexToMask( string bits)
        {
            if (bits.Contains("[")&& bits.Contains("]"))
            {
                var bitsTemp = bits.Replace("[", "").Replace("]", "").Split(':');
                int max = bitsTemp.Max(c => int.Parse(c));
                int min = bitsTemp.Min(c => int.Parse(c));
                string binary = "";
                if (max == min && max <= 7)
                {
                    for (int z = 7; z > -1; z--)
                    {
                        if (z == max)
                        {
                            binary += "1";
                        }
                        else
                        {
                            binary += "0";
                        }
                    }

                }
                else
                {
                    for (int z = 0; z <= max - min; z++)
                    {
                        binary += "1";
                    }
                }

                return string.Format("{0:X}", System.Convert.ToInt32(binary, 2));
            }
            else
            {
                return "FF";
            }
          
        }

      

        

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textEdit1.Text))
            {
                var aut = gongnengEdit.EditValue.ToString();
                var list = r151List.Where(c => c.Author == aut &&( c.Address.Contains(textEdit1.Text) || c.BaseAddr.Contains(textEdit1.Text) || c.AddrOffset.Contains(textEdit1.Text))).ToList();
                gridControl1.DataSource = list;
                this.gridControl2.DataSource = null;
                gridView2.RefreshData();
                gridView1.RefreshData();
                return;
            }
            else
            {
                var aut = gongnengEdit.EditValue.ToString();
                var list = r151List.Where(c => c.Author == aut).ToList();
                gridControl1.DataSource = list;
                this.gridControl2.DataSource = null;
                gridView2.RefreshData();
                gridView1.RefreshData();
            }
        }
    }

  
}
